import axios from 'axios'

const instance = axios.create({
  baseURL: '/api',
  timeout: 300_000 // 延长超时时间到5分钟
})

instance.interceptors.request.use((config) => {
  // 从localStorage中获取token，而不是直接调用useAuthStore()
  const token = localStorage.getItem('token')
  if (token) config.headers.Authorization = `Bearer ${token}`
  return config
})

instance.interceptors.response.use(
  (res) => {
    // 检查响应是否包含data字段
    const responseData = res.data || res;
    
    // 如果响应包含data字段，且data是对象，返回data.data
    // 这是因为后端返回的格式是 { data: {...}, msg: "..." }
    if (responseData.data && typeof responseData.data === 'object') {
      return responseData.data;
    }
    
    // 否则返回响应数据
    return responseData;
  },
  (err) => {
    if (err.response?.status === 401) {
      // 清除localStorage中的登录信息
      localStorage.removeItem('token')
      localStorage.removeItem('role')
      localStorage.removeItem('userData')
      localStorage.removeItem('rememberMe')
      localStorage.removeItem('loginTime')
      window.location.replace('/auth/login')
    }
    return Promise.reject(err)
  }
)

export default instance
